package com.cos.shop.dao.impl;

import com.cos.shop.common.Const;
import com.cos.shop.dao.AddressDao;
import com.cos.shop.entity.Address;
import com.cos.shop.util.JDBCUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * @author: COS
 * @time: 2022/2/24 14:34
 * @description:
 */
public class AddressDaoImpl implements AddressDao {
    private QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());

    @Override
    public int setAddressNoneDefault(int uid) throws SQLException {
        return qr.update("update address set astate =? where uid = ?",Const.NOT_DEFAULT_ADDRESS,uid);
    }

    @Override
    public int setDefault(int aid) throws SQLException {
        return qr.update("update address set astate = ? where aid = ?",
                Const.DEFAULT_ADDRESS,aid);
    }

    @Override
    public int update(Address a) throws SQLException {
        return qr.update("update address set aname=?,aphone=?,adetail=? where aid=?",
                a.getAname(),a.getAphone(),a.getAdetail(),a.getAid());
    }

    @Override
    public int delete(int aid) throws SQLException {
        return qr.update("delete from address where aid = ?",aid);
    }

    @Override
    public int insertAddress(Address a) throws SQLException {
        return qr.update("insert into address values (default,?,?,?,?,?)",
                a.getUid(),a.getAname(),a.getAphone(),a.getAdetail(),a.getAstate());
    }

    @Override
    public List<Address> getAddressListByUid(int uid) throws SQLException {
        return qr.query("select * from address where uid = ? order by astate desc",new BeanListHandler<>(Address.class),uid);
    }
}
